package models

import (
	"GoTime/models/response"
	. "GoTime/utils"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/spf13/cast"
)

type School struct {
	Id                int     `xorm:"not null pk autoincr comment('自增主键') INT(11)" json:"id"`
	UserId            int     `xorm:"not null comment('用户id,外键关联dts_user中的id') index INT(11)" json:"user_id"`
	Config            int     `xorm:"not null comment('驾校配置,一个驾校可以有多个配置,此处配置为当前生效配置') INT(11)" json:"config"`
	InstitutionCode   string  `xorm:"default '' comment('培训机构编号运管中心颁发初始为空') VARCHAR(16)" json:"institution_code"`
	District          string  `xorm:"not null comment('区县行政区规划码') CHAR(6)" form:"district" json:"district"`
	Name              string  `xorm:"not null comment('驾校名称') VARCHAR(60)" form:"name" json:"name"`
	NameShort         string  `xorm:"not null comment('驾校简称') VARCHAR(16)" form:"name_short" json:"name_short"`
	LicenceNumber     string  `xorm:"not null comment('驾校经营许可证编号') CHAR(13)" form:"licence_number" json:"licence_number"`
	LicenceGrantTime  string  `xorm:"not null comment('驾校经营许日期 YYYYMMDD') DATE" form:"licence_grant_time" json:"licence_grant_time"`
	LicenceEndTime    string  `xorm:"not null comment('驾校经营许日期 YYYYMMDD') DATE" form:"licence_end_time" json:"licence_end_time"`
	BusinessNumber    string  `xorm:"not null comment('驾校营业执照注册号') CHAR(20)" form:"business_number" json:"business_number"`
	CreditCode        string  `xorm:"default '' comment('驾校统一社会信用代码') CHAR(18)" form:"credit_code" json:"credit_code"`
	Address           string  `xorm:"not null comment('驾校地址') VARCHAR(512)" form:"address" json:"address"`
	Postcode          string  `xorm:"not null comment('邮政编码') CHAR(6)" form:"postcode" json:"postcode"`
	Legal             string  `xorm:"not null comment('法人代表') VARCHAR(64)" form:"legal" json:"legal"`
	Contact           string  `xorm:"not null comment('联系人') VARCHAR(64)" form:"contact" json:"contact"`
	Phone             string  `xorm:"not null comment('联系电话') VARCHAR(32)" form:"phone" json:"phone"`
	BusinessScope     string  `xorm:"not null comment('经营范围') VARCHAR(255)" form:"business_scope" json:"business_scope"`
	BusinessStatus    string  `xorm:"default '9' comment('1:营业,2:停业,3:整改,4:停业整顿,5:歇业,6:注销,9:其他') ENUM('1','2','3','4','5','6','9')" form:"business_status" json:"business_status"`
	Level             string  `xorm:"not null comment('驾校分类等级1:一级,2:二级,3:三级') ENUM('1','2','3')" form:"level" json:"level"`
	CoachCount        int64   `xorm:"not null comment('教练员总数') BIGINT(16)" form:"coach_count" json:"coach_count"`
	CarCount          int64   `xorm:"not null comment('教练车总数') BIGINT(16)" form:"car_count" json:"car_count"`
	GrasupvNum        int64   `xorm:"default 0 comment('考核员总数') BIGINT(16)" form:"grasupv_num" json:"grasupv_num"`
	SafmngNum         int64   `xorm:"default 0 comment('安全员总数') BIGINT(16)" form:"safmng_num" json:"safmng_num"`
	ClassroomArea     int64   `xorm:"default 0 comment('教室总面积 单位:平方米') BIGINT(16)" form:"classroom_area" json:"classroom_area"`
	ThclassroomArea   int64   `xorm:"default 0 comment('理论教室面积  单位:平方米') BIGINT(16)" form:"thclassroom_area" json:"thclassroom_area"`
	PraticefieldArea  int64   `xorm:"default 0 comment('训练场总面积 单位:平方米') BIGINT(16)" form:"praticefield_area" json:"praticefield_area"`
	ApprovalStatus    string  `xorm:"default '0' comment('驾校提交运管审核状态,0:待审核,1:通过审核,2:未通过审核') ENUM('0','1','2')" json:"approval_status"`
	RecordStatus      string  `xorm:"default '0' comment('备案状态 0:未备案 1:已备案') VARCHAR(1)" json:"record_status"`
	RecordStatus2     string  `xorm:"default '0' comment('濮阳备案状态 0:未备案 1:已备案') VARCHAR(1)"`
	BaseaddStatus     string  `xorm:"default '0' comment('培训机构预录入状态 0:未预录入  1:已预录入') ENUM('0','1')" json:"baseadd_status"`
	Province          string  `xorm:"default '' comment('省') index CHAR(10)" form:"province" json:"province"`
	City              string  `xorm:"default '' comment('市') CHAR(10)" form:"city" json:"city"`
	Money             int     `xorm:"default 0 comment('可以提现总金额 单位 毫') INT(11)" json:"money"`
	Registernum       int64   `xorm:"not null default 30 comment('可注册学员数') INT(11)" json:"registernum"`
	Usednum           int64   `xorm:"not null default 0 comment('已注册学员数') INT(11)" json:"usednum"`
	Schoolcode        string  `xorm:"comment('驾校代码') VARCHAR(255)" json:"schoolcode"`
	Registeredcapital float32 `xorm:"default 0 comment('注册资金') FLOAT(20)" form:"registeredcapital" json:"registeredcapital"`
	Remark            string  `xorm:"comment('备注') VARCHAR(255)" json:"remark"`
	Signmoney         float64 `xorm:"default 50.0 comment('默认该驾校的金额') FLOAT(11,1)" json:"signmoney"`
	Remainnum         int     `xorm:"INT(11)" json:"remainnum"`
	Isused            string  `xorm:"ENUM('0','1')" json:"isused"`
	Xiaozhangsignurl  string  `xorm:"VARCHAR(255)" json:"xiaozhangsignurl"`
	Zhangurl          string  `xorm:"VARCHAR(255)" json:"zhangurl"`
	Lownum            int64   `xorm:"default 100 INT(11)" json:"lownum"`
	Addtime           string  `xorm:"TIMESTAMP" json:"addtime"`
	Status            int     `xorm:"default 0 comment('0为正常1为禁用') TINYINT(4)" json:"status"`
	Transfertype      string  `xorm:"default '1' comment('0 Tcp 1 HTTP 传输类型') ENUM('0','1')" json:"transfertype"`
	Pacttype          string  `xorm:"default '0' comment('默认0 1代表万正  2代表驾航') ENUM('0','1','2')" json:"pacttype"`
	BusinessProject   string  `xorm:"VARCHAR(255)" form:"business_project" json:"businessProject"`
}

// SchoolLogin 用户登录
func (s *School) SchoolLogin(username string) (school response.SchoolRole, err error) {
	_, err = engine.Table("dts_school").Alias("sl").
		Select("sl.id,sl.user_id,u.password,sl.name_short,sl.institution_code,sl.province,sl.city,sl.district,sl.pacttype").
		Join("LEFT", []string{"dts_user", "u"}, "sl.user_id = u.id").
		Where("u.name = ? and u.type = ? and sl.isused = ?", username, "2", "1").
		Get(&school)
	log.Println(err)
	return
}

// GetSchoolDetailById 获取驾校详情
func (s *School) GetSchoolDetailById(id string) (ok bool, school response.SchoolDetailResp, err error) {
	ok, err = engine.Table("dts_school").
		Where("id = ? and isused = ?", id, "1").
		Get(&school)
	//log.Print(err)
	return
}

// GetSchoolById 获取驾校详情
func (s *School) GetSchoolById(id interface{}) (ok bool, school School, err error) {
	ok, err = engine.Table("dts_school").
		Where("id = ? and isused = ?", id, "1").
		Get(&school)
	return
}

func (s *School) Institution(province string, city string) (list *School, err error) {
	var (
		url     string
		retMap  map[string]interface{}
		reqType int64
	)
	//培训机构备案信息
	data := map[string]interface{}{
		"district":     s.District,                                       //区县行政区划代码
		"name":         s.Name,                                           //培训机构名称
		"shortname":    s.NameShort,                                      //培训机构简称
		"licnum":       s.LicenceNumber,                                  //经营许可证编号
		"licetime":     strings.Replace(s.LicenceGrantTime, "-", "", -1), //经营许可日期
		"business":     s.BusinessNumber,                                 //营业执照注册号
		"creditcode":   s.CreditCode,                                     //统一社会信用代码
		"address":      s.Address,                                        //培训机构地址
		"postcode":     s.Postcode,                                       //邮政编码
		"legal":        s.Legal,                                          //法人代表
		"contact":      s.Contact,                                        //联系人
		"phone":        s.Phone,                                          //联系电话
		"busiscope":    s.BusinessScope,                                  //经营范围
		"busistatus":   s.BusinessStatus,                                 //经营状态
		"level":        s.Level,                                          //分类等级
		"coachnumber":  s.CoachCount,                                     //教练员总数
		"grasupvnum":   s.GrasupvNum,                                     //考核员总数
		"safmngnum":    s.SafmngNum,                                      //安全员总数
		"tracarnum":    s.CarCount,                                       //教练车总数
		"classroom":    s.ClassroomArea,                                  //教室总面积
		"thclassroom":  s.ThclassroomArea,                                //理论教室面积
		"praticefield": s.PraticefieldArea,                               //教练场总面积
	}
	fmt.Println(data)
	reqType = 1
	if url, err = GetSignURL("institution", data, reqType, province, city); err != nil {
		return s, err
	}
	fmt.Println(url)
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var api_log ApiLog
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		return s, err
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorcode := cast.ToInt(retMap["errorcode"])
	if errorcode != 0 {
		return s, errors.New(retMap["message"].(string))
	}
	if md, ok := retMap["data"].(map[string]interface{}); ok {
		s.InstitutionCode = fmt.Sprint(md["inscode"])
		return s, nil
	}
	return s, errors.New("获取培训机构编号失败")
}
func (s *School) RecordSchool() (err error) {
	var (
		url     string
		retMap  map[string]interface{}
		reqType int64
	)
	if s.InstitutionCode == "" {
		s.InstitutionCode = GetInstitutionCode(s.CreditCode)
	}
	//培训机构备案信息
	data := map[string]interface{}{
		"inscode":         s.InstitutionCode,                                //培训机构编号
		"district":        s.District,                                       //区县行政区划代码
		"name":            s.Name,                                           //培训机构名称
		"shortname":       s.NameShort,                                      //培训机构简称
		"licnum":          s.LicenceNumber,                                  //经营许可证编号
		"licetime":        strings.Replace(s.LicenceGrantTime, "-", "", -1), //经营许可日期
		"liceendtime":     strings.Replace(s.LicenceEndTime, "-", "", -1),   //经营许可截止日志
		"business":        s.BusinessNumber,                                 //营业执照注册号
		"creditcode":      s.CreditCode,                                     //统一社会信用代码
		"address":         s.Address,                                        //培训机构地址
		"postcode":        s.Postcode,                                       //邮政编码
		"legal":           s.Legal,                                          //法人代表
		"contact":         s.Contact,                                        //联系人
		"phone":           s.Phone,                                          //联系电话
		"busiscope":       s.BusinessScope,                                  //经营范围
		"busistatus":      s.BusinessStatus,                                 //经营状态
		"level":           s.Level,                                          //分类等级
		"coachnumber":     s.CoachCount,                                     //教练员总数
		"grasupvnum":      s.GrasupvNum,                                     //考核员总数
		"safmngnum":       s.SafmngNum,                                      //安全员总数
		"tracarnum":       s.CarCount,                                       //教练车总数
		"classroom":       s.ClassroomArea,                                  //教室总面积
		"thclassroom":     s.ThclassroomArea,                                //理论教室面积
		"praticefield":    s.PraticefieldArea,                               //教练场总面积
		"businessproject": s.BusinessProject,                                //经营项目
	}
	if s.City == "130100" {
		reqType = 3
	} else {
		reqType = 2
	}
	if url, err = GetSignURL("institution", data, reqType, s.Province, s.City); err != nil {
		return err
	}
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var api_log ApiLog
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		return err
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	switch retMap["errorcode"].(type) {
	case float64:
		if retMap["errorcode"].(float64) != 0 {
			return errors.New(retMap["message"].(string))
		}
	case string:
		if retMap["errorcode"].(string) != "0" {
			return errors.New(retMap["message"].(string))
		}
	}
	s.RecordStatus = "1"
	if !s.EditSchool("record_status", "institution_code") {
		return errors.New("编辑失败")
	}
	return nil
}

func (s *School) EditSchool(fields ...string) bool {
	var (
		err error
	)
	_, err = engine.ID(s.Id).Cols(fields...).Update(s)
	if err != nil {
		return false
	}
	return true
}

func (s *School) SchoolLicNumChange(licNum, province, city string) (err error) {
	var (
		url     string
		retMap  map[string]interface{}
		reqType int64
	)
	//培训机构备案信息
	data := map[string]interface{}{
		"inscode":    s.InstitutionCode, //培训机构编号
		"platnum":    "A0033",           // 哈哈计时平台
		"befinscode": s.InstitutionCode, //原机构编号
		"licnum":     licNum,            //经营许可证编号
		"beflicnum":  s.LicenceNumber,   //原经营许可证编号
	}
	if city == "130100" {
		reqType = 3
	} else {
		reqType = 2
	}
	if url, err = GetSignURL("licnumchange", data, reqType, province, city); err != nil {
		return err
	}
	param, err := json.Marshal(data)
	if err != nil {
		fmt.Println("json.Marshal failed:", err)
		return
	}
	var apiLog ApiLog
	apiLog.Url = url
	apiLog.Param = string(param)
	apiLog.Method = "POST"
	apiLog.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		apiLog.Result = string(result)
		apiLog.Add()
		return err
	}
	result, _ := json.Marshal(retMap)
	apiLog.Result = string(result)
	apiLog.Add()
	switch retMap["errorcode"].(type) {
	case float64:
		if retMap["errorcode"].(float64) != 0 {
			return errors.New(retMap["message"].(string))
		}
	case string:
		if retMap["errorcode"].(string) != "0" {
			return errors.New(retMap["message"].(string))
		}
	}
	//s.InstitutionCode = "1"
	//if !s.EditSchool("institution_code") {
	//	return errors.New("编辑失败")
	//}
	return nil
}
